﻿using SD.Infrastructure.Repository.EntityFrameworkCore;
using SD.Infrastructure.RepositoryBase;
using SlamDunk.MES.Domain.Entities.ResourceContext;
using SlamDunk.MES.Domain.IRepositories.Interfaces.ResourceContext;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace SlamDunk.MES.Repository.Implements.ResourceContext
{
    /// <summary>
    /// 人员仓储实现
    /// </summary>
    public class PersonRepository : EFAggRootRepositoryProvider<Person>, IPersonRepository
    {
        #region # 分页获取人员列表 —— ICollection<Person> FindByPage(string keywords...
        /// <summary>
        /// 分页获取人员列表
        /// </summary>
        /// <param name="keywords">关键字</param>
        /// <param name="facilityIds">工厂模型Id集</param>
        /// <param name="personClassIds">人员类Id集</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页容量</param>
        /// <param name="rowCount">总记录数</param>
        /// <param name="pageCount">总页数</param>
        /// <returns>人员列表</returns>
        public ICollection<Person> FindByPage(string keywords, IList<Guid> facilityIds, IList<Guid> personClassIds, int pageIndex, int pageSize, out int rowCount, out int pageCount)
        {
            Expression<Func<Person, bool>> condition =
                x =>
                    (string.IsNullOrEmpty(keywords) || x.Keywords.Contains(keywords));

            IQueryable<Person> persons = base.Find(condition);
            if (facilityIds != null && facilityIds.Any())
            {
                persons = persons.Where(x => x.FacilityId.HasValue && facilityIds.Contains(x.FacilityId.Value));
            }
            if (personClassIds != null && personClassIds.Any())
            {
                persons = persons.Where(x => x.RelatedClasses.Any(y => personClassIds.Contains(y.PersonClassId)));
            }

            IOrderedQueryable<Person> orderedResult = persons.OrderByDescending(x => x.AddedTime);
            IQueryable<Person> pagedResult = orderedResult.ToPage(pageIndex, pageSize, out rowCount, out pageCount);

            return pagedResult.ToList();
        }
        #endregion
    }
}
